<template>
  <a-card :bordered="false">
      <!-- 查询区域 -->
    <div class="table-page-search-wrappe">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="开票日期" style="height: 32px;">
              <a-range-picker
              :allowClear="false"
              v-model="invitation"
              style="width: 100%"
              @change="invitationChange"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="开票公司">
              <select-Company-input placeholder="请选择开票公司" v-model="queryParam.sellerUnit" :multi="true"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="所属团队">
              <select-team-input placeholder="请选择团队"  v-model="queryParam.teamId" :teamType="0" :tdlx="3" :multi="true" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="项目名称">
              <select-project-input v-model="queryParam.projectId" placeholder="请选择项目" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="开票金额">
              <a-input-number :min="0" :precision="0" style="width: 45%" placeholder="请输入中标金额最小值" class="query-group-cust" v-model="queryParam.invoiceAmountBegin"></a-input-number>
              <span class="query-group-split-cust"></span>
              <a-input-number :min="queryParam.invoiceAmountBegin" :precision="0" style="width: 45%" placeholder="请输入中标金额最大值" class="query-group-cust" v-model="queryParam.invoiceAmountEnd"></a-input-number>
            </a-form-item>
          </a-col>
          <!-- <template v-if="toggleSearchStatus"></template> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="onClearSelected();searchQuery();" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls('开票申请台账')" :disabled="isDisabledAuth('erpFinanceInvoiceStanding:export')">导出</a-button>
      <!-- 高级查询区域 -->
      <!--<j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <a-popover title="自定义列" trigger="click" placement="leftBottom">
        <template slot="content">
          <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
            <a-row>
              <template v-for="(item,index) in defColumns">
                <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                  <a-col :span="12" :key="index"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>
                </template>
              </template>
            </a-row>
          </a-checkbox-group>
        </template>
        <a style="float: right;"><a-icon type="setting" :style='iconStyle'/></a>
      </a-popover>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x: scrollX}"
        :components="draggableComponent"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">
        <a slot="invoiceAmount" slot-scope="text, record" @click="onDetail(record.billId)">{{ text }}</a>
        <a slot="projectId" slot-scope="text, record" @click="onProjectDetail(record.projectId)">{{ text }}</a>
      </a-table>
    </div>
    <!-- 开票申请详情开始 -->
    <a-modal
      :maskClosable="false"
      title="开票申请单据详情"
      :width="1350"
      :bodyStyle="{
        padding: '0 24px'
      }"
      :visible="visibleDetail"
      @cancel="handleCancelDetail"
      cancelText="关闭">
      <erp-finance-invoice-application-bill-form ref="invoiceForm" :disabled="true" normal></erp-finance-invoice-application-bill-form>
      <template slot="footer">
        <a-button @click.stop="handleCancelDetail">关闭</a-button>
      </template>
    </a-modal>
    <!--开票申请详情结束 -->
    <!-- 项目详情开始 -->
    <erp-project-report-modal  ref="projectForm"></erp-project-report-modal>
    <!-- 项目详情结束 -->
  </a-card>
</template>
<script>
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import {DisabledAuthFilterMixin} from '@/mixins/DisabledAuthFilterMixin'
  import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
  import moment from 'moment'
  import {getAction} from '@/api/manage'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput';
  import ErpFinanceInvoiceApplicationBillForm from '@/views/erp/finance/invoice/modules/ErpFinanceInvoiceApplicationBillForm'
  import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
  export default {
    name: 'ErpFinanceInvoiceStandingList',
    mixins:[JeecgListMixin, mixinDevice, DisabledAuthFilterMixin],
    components: {
      ErpProjectReportModal,
      SelectTeamInput,
      SelectProjectInput,
      SelectCompanyInput,
      ErpFinanceInvoiceApplicationBillForm
    },
    data () {
      return {
        description: '开票申请台账管理页面',
        //表头
        columns:[],
        //列设置
        settingColumns:[],
        // 列定义
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'开票公司',
            align:"center",
            dataIndex: 'sellerUnit_dictText',
            width: 300,
            ellipsis: true,
          },
          {
            title:'开票日期',
            align:"center",
            dataIndex: 'invoiceTime',
            ellipsis: true,
            width: 167,
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'购买方单位名称',
            align:"center",
            dataIndex: 'buyerUnit_dictText',
            width: 300,
            ellipsis: true,
          },
          {
            title:'项目编号',
            align:"center",
            dataIndex: 'projectNo',
            ellipsis: true,
            width: 167,
          },
          {
            title:'项目名称',
            align:"center",
            dataIndex: 'projectId_dictText',
            scopedSlots: { customRender: 'projectId' },
            ellipsis: true,
            width: 167,
          },
          {
            title:'合同金额（元）',
            align:"center",
            dataIndex: 'bchte',
            ellipsis: true,
            width: 167,
          },
          {
            title:'开票金额（元）',
            align:"center",
            dataIndex: 'invoiceAmount',
            scopedSlots: { customRender: 'invoiceAmount' },
            ellipsis: true,
            width: 167,
          },
          {
            title:'税率（%）',
            align:"center",
            dataIndex: 'taxRate',
            ellipsis: true,
            width: 167,
          },
          {
            title:'所属板块',
            align:"center",
            dataIndex: 'businessSegment',
            ellipsis: true,
            width: 167,
          },
          {
            title:'业务类型',
            align:"center",
            dataIndex: 'businessType',
            ellipsis: true,
            width: 167,
          },
          {
            title:'发票类型',
            align:"center",
            dataIndex: 'invoiceCategory_dictText',
            ellipsis: true,
            width: 167,
          },
          {
            title:'所属年度',
            align:"center",
            dataIndex: 'attributionYear_dictText',
            ellipsis: true,
            width: 167,
          },
          {
            title:'所属团队',
            align:"center",
            dataIndex: 'teamId_dictText',
            ellipsis: true,
            width: 167,
          },
          {
            title:'开票申请人',
            align:"center",
            dataIndex: 'invoiceApplicant_dictText',
            ellipsis: true,
            width: 167,
          },
          {
            title:'承接人',
            align:"center",
            dataIndex: 'undertaker_dictText',
            ellipsis: true,
            width: 167,
          },
          {
            title:'预计回款时间',
            align:"center",
            dataIndex: 'estimateRefundTime',
            ellipsis: true,
            width: 167,
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'invoiceRemark',
            width: 200,
            ellipsis: true,
          },
        ],
        url: {
          list: "/api/erp/finance/statistical/erpFinanceInvoiceStanding/list",
          exportXlsUrl: "/api/erp/finance/statistical/erpFinanceInvoiceStanding/exportXls",
          queryById: '/api/erp/finance/invoice/erpFinanceInvoiceApplicationBill/queryById',
          queryByProjectId: '/api/erp/project/report/erpProjectReport/queryById'
        },
        dictOptions:{},
        superFieldList:[],
        invitation: [],
        invitationStartTime: null,
        invitationEndTime: null,
        visibleDetail: false,
      }
    },
    created() {
      this.getSuperFieldList();
    },
    methods: {
      moment,
      loadData(arg) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        if(this.invitation.length == 0) {
          this.initMonthDate()
        }
        var params = this.getQueryParams() // 查询条件
        this.loading = true
        getAction(this.url.list, params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            //判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },
      //初始化合同签订日期查询条件
      initMonthDate() {
        let date = new Date();//当前时间
        let year= date.getFullYear();//获取当前年
        let month = date.getMonth()  + 1;//获取当前月
        let day = date.getDate();//获取当前日
        month = (month > 9) ? month : ("0" + month);//设置 月份格式
        day = (day < 10) ? ("0" + day) : day;//设置 日格式
        let today = year + "-" + month + "-" + day;//当前日期
      
        let invitationStartTime = year +'-01-01';
        let invitationEndTime = today;
        this.invitation = [moment(invitationStartTime, 'YYYY-MM-DD'), moment(invitationEndTime, 'YYYY-MM-DD')]
        this.$set(this.queryParam, 'invitationStartTime', invitationStartTime + ' 00:00:00')
        this.$set(this.queryParam, 'invitationEndTime', invitationEndTime + ' 23:59:59')
      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'sellerUnit',text:'开票公司',dictCode:''})
        fieldList.push({type:'date',value:'invoiceTime',text:'开票日期',dictCode:''})
        fieldList.push({type:'string',value:'buyerUnit',text:'购买方单位名称',dictCode:''})
        fieldList.push({type:'string',value:'projectNo',text:'项目编号',dictCode:''})
        fieldList.push({type:'string',value:'projectId',text:'项目名称'})
        fieldList.push({type:'BigDecimal',value:'bchte',text:'合同金额（元）',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'invoiceAmount',text:'开票金额（元）',dictCode:''})
        fieldList.push({type:'string',value:'taxRate',text:'税率（%）',dictCode:''})
        fieldList.push({type:'string',value:'businessSegment',text:'所属板块',dictCode:''})
        fieldList.push({type:'string',value:'businessType',text:'业务类型',dictCode:''})
        fieldList.push({type:'string',value:'invoiceCategory',text:'发票类型',dictCode:''})
        fieldList.push({type:'string',value:'attributionYear',text:'所属年度',dictCode:''})
        fieldList.push({type:'string',value:'teamId',text:'所属团队',dictCode:''})
        fieldList.push({type:'string',value:'invoiceApplicant',text:'开票申请人',dictCode:''})
        fieldList.push({type:'string',value:'undertaker',text:'承接人',dictCode:''})
        fieldList.push({type:'date',value:'estimateRefundTime',text:'预计回款时间',dictCode:''})
        fieldList.push({type:'string',value:'invoiceRemark',text:'备注',dictCode:''})
        this.superFieldList = fieldList
      },
      invitationChange(date, dateString) {
        this.$set(this.queryParam, 'invitationStartTime', dateString[0] + ' 00:00:00')
        this.$set(this.queryParam, 'invitationEndTime', dateString[1] + ' 23:59:59')
      },
      searchReset() {
        this.invitation = []
        this.queryParam = {}
        this.loadData(1)
      },
      onDetail(billId) {
        this.visibleDetail = true
        this.$nextTick(()=>{
          const id = billId;
          getAction(this.url.queryById, { id }).then((res) => {
            if (res.success) {
              const model = res.result
              this.$refs.invoiceForm.edit(model);
            }
          })
        });
      },
      handleCancelDetail() {
        this.visibleDetail = false
      },
      onProjectDetail(id) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryByProjectId, { id: id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectForm.getDetail(model);
              that.$refs.projectForm.title = '项目一览表';
            }
          })
        })
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
